<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="发起活动" v-if="this.$store.state.user.info.companyType != '0' && enterpriseName ===null">
        <training></training>
      </el-tab-pane>
      <el-tab-pane label="参加活动">
        <el-row>
          <el-col :span="24">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"   v-if="showClose === false"
              label-width="68px">
              <el-form-item label="活动名称" prop="activityName">
                <el-input v-model="queryParams.activityName" placeholder="请输入活动名称" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="活动时间" prop="initiationTime">
                <el-date-picker clearable v-model="queryParams.initStartTime" type="datetime"
                  value-format="yyyy-MM-dd HH:mm" placeholder="请选择开始时间">
                </el-date-picker>
                至
                <el-date-picker clearable v-model="queryParams.initEndTime" type="datetime"
                  value-format="yyyy-MM-dd HH:mm" placeholder="请选择结束时间">
                </el-date-picker>
              </el-form-item>



              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
            <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
            <el-table :row-style="{ height: '30px' }" :cell-style="{ padding: '0px' }" height="450" border
              v-loading="loading" :data="trainingList" highlight-current-row>
              <el-table-column label="序号" align="center" type="index" :index="indexMethod" />
              <el-table-column label="状态" align="center" prop="status" v-if="columns[0].visible" />
              <el-table-column label="活动名称" align="center" prop="activityName" width="200" v-if="columns[1].visible"
                :show-overflow-tooltip="true" />
              <el-table-column label="主办单位" align="center" prop="sponsor" v-if="columns[3].visible"
                :show-overflow-tooltip="true" width="200" />
              <el-table-column label="类别" align="center" prop="type" v-if="columns[4].visible"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.activity_type" :value="scope.row.type" />
                </template>
              </el-table-column>
              <el-table-column label="发起时间" align="center" prop="initiationTime" width="180" v-if="columns[5].visible">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.initiationTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="形式" align="center" prop="lays" v-if="columns[5].visible" />
              <el-table-column label="开始时间" align="center" prop="startTime" width="130" v-if="columns[6].visible">
                <template slot-scope="scope">
                  <span>{{ parseUTCTime(scope.row.startTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" prop="endTime" width="130" v-if="columns[7].visible">
                <template slot-scope="scope">
                  <span>{{ parseUTCTime(scope.row.endTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="地点" align="center" prop="location" v-if="columns[8].visible"
                :show-overflow-tooltip="true" />
              <el-table-column label="联系人" align="center" prop="contacts" v-if="columns[12].visible"
                :show-overflow-tooltip="true" />
              <el-table-column label="联系电话" align="center" prop="telephone" v-if="columns[13].visible"
                :show-overflow-tooltip="true" />
              <el-table-column label="报名截止" align="center" prop="deadlineTime" width="120" v-if="columns[14].visible">
                <template slot-scope="scope">
                  <span>{{ parseUTCTime(scope.row.deadlineTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="是否报名" align="center" prop="partRecive" v-if="columns[18].visible" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                  <el-button :disabled="!(scope.row.status == '报名' && isBeforeDeadline(scope.row.deadlineTime))"
                    size="mini" type="text" icon="el-icon-edit" @click="handleSelect(scope.row, scope.$index)"
                    v-if="enterpriseId == ''" title="报名"></el-button>
                  <el-button v-if="scope.row.status !== '审核' || this.enterpriseId!==''" size="mini" type="text" icon="el-icon-view"
                    @click="handleScore(scope.row.activityId, scope.$index)" title="查看"></el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
            </div>
          </el-col>
        </el-row>
        <!-- 添加或修改活动信息培训对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="closeTrain">
          <el-form ref="form" :model="form" label-width="80px" :inline="true">
            <div v-if="addSign !== 0">
              <el-descriptions title="">
                <el-descriptions-item label="序号">
                  <el-tag size="medium">{{ form.index }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <el-form-item label="活动名称" prop="activityName" label-width="110px">
              <el-input v-model="form.activityName" placeholder="请输入活动名称" :disabled="ReadOnly" style="width: 202.5px" />
            </el-form-item>
            <el-form-item label="发起时间" prop="initiationTime" label-width="110px">
              <el-date-picker clearable v-model="form.initiationTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择发起时间" style="width: 202.5px" :disabled="ReadOnly">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="主办单位" prop="sponsor" label-width="110px">
              <el-input v-model="form.sponsor" type="textarea" placeholder="请选择主办单位"  :disabled="ReadOnly"
                style="width: 525px" />
            </el-form-item>
            <el-form-item label="协办单位" prop="organizer" label-width="110px">
              <el-input v-model="form.organizer" type="textarea" placeholder="请选择协办单位"  :disabled="ReadOnly"
                style="width: 525px" />
            </el-form-item>
            <el-form-item label="承办单位" prop="undertaker" label-width="110px">
              <el-input v-model="form.undertaker" type="textarea" placeholder="请选择承办单位"  :disabled="ReadOnly"
                style="width: 525px" />
            </el-form-item>
            <el-form-item label="类别" prop="type" label-width="110px">
              <el-select v-model="form.type" placeholder="请选择形式" style="width: 100%;" :disabled="ReadOnly">
                <el-option v-for="dict in dict.type.activity_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" width="178px"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="形式" prop="lays" label-width="120px">
              <el-select v-model="form.lays" placeholder="请选择形式" style="width: 202.5px" :disabled="ReadOnly">
                <el-option label="线下" value="线下"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime" label-width="110px">
              <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm" :disabled="ReadOnly" :picker-options="{ disabledDate: dateOptions }"
                style="width: 202.5px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime" label-width="110px">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm" :disabled="ReadOnly" :picker-options="{ disabledDate: dateOptions }"
                style="width: 202.5px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="地点" prop="location" label-width="110px">
              <el-input v-model="form.location" placeholder="请输入地点" :disabled="ReadOnly" style="width: 202.5px"
                :title="ReadOnly ? form.location : ''" />
            </el-form-item>
            <el-form-item label="联系人" prop="contacts" label-width="110px">
              <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="ReadOnly" style="width: 202.5px" />
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone" label-width="110px">
              <el-input v-model="form.telephone" placeholder="请输入联系电话" :disabled="ReadOnly" style="width: 202.5px" />
            </el-form-item>
            <el-form-item label="区域" prop="region" label-width="110px">
              <Treeselect v-model="form.region" :options="optionsArea" style="width: 202.5px" :flat="true"
                :show-count="true" :normalizer="normalizer" placeholder="请选择区域" :disabled="ReadOnly" />
            </el-form-item>
            <el-form-item label="报名截止" prop="deadlineTime" label-width="110px">
              <el-date-picker clearable v-model="form.deadlineTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                placeholder="请选择报名截止" style="width: 202.5px" :disabled="ReadOnly">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="附件" prop="uploadFile" label-width="110px">
              <file-view v-if="show" :limit="1" :type="typeSelect" :businessId="form.fileUpload"
                :businessCode="businessCode" style="width: 500px"></file-view>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center; align-items: center;">
            <el-button type="primary" @click="submitForm(form.activityId)" v-if="form.status === '审核'">审 核</el-button>
            <el-button @click="cancel">关 闭</el-button>
          </div>

        </el-dialog>
        <el-dialog :title="title" :visible.sync="openUser" width="1400px" append-to-body>
          <el-scrollbar>

            <div class="content-box">
              <BusinessInfo :markAs="1" @change="close" @ok="selectEnterprise" :enterprise="1" :isTree="false"
                :train="true">

              </BusinessInfo>
            </div>
          </el-scrollbar>
        </el-dialog>
        <el-dialog title="报名人员" :visible.sync="openApplication" width="1000px" append-to-body v-if="openApplication"
          @close="openPerson">
          <receive-person :activity-id="activityId" :activity-name="form.activityName"></receive-person>
        </el-dialog>
        <select-user ref="select" :type="userType" :sign="sign" @ok="selectUser"></select-user>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getTraining, examine, listTrainingRevice, receiveApplication, listTrainingByEnterpriseId } from "@/api/activity/training";
import { listType } from "@/api/maintype/type";
import MainType from "@/components/MainType/index"
import FileView from "@/components/FileView/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import BusinessInfo from "../../enterprise/info/index.vue";
import SelectUser from "../../system/role/selectUser.vue";
import ReceivePerson from "./receivePerson.vue";
import { listArea } from "@/api/area/area";
import Training from "../training/index.vue";
export default {
  name: "receive",
  components: { Training, ReceivePerson, SelectUser, BusinessInfo, Treeselect, MainType, FileView },
  props: {
    enterpriseId: {
      type: String,
      default: ""
    },
    enterpriseName:{
      type: String,
      default: null
    },
    showClose: {
      type: Boolean,
      default: false
    },
  },
  dicts: ['activity_type'],
  data() {
    return {
      // 日期选择器选项
      dateOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // Disable dates before today
        }
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      isSign: false,
      ids: null,
      // 总条数
      total: 0,
      typeCode: 'train',
      // 活动信息培训表格数据
      trainingList: [],
      // 弹出层标题
      title: "",
      //详情状态
      ReadOnly: false,
      // 是否显示弹出层
      open: false,
      //判断对话框是否新增或编辑
      addSign: 0,
      activityId: null,
      //图片的标志位
      show: false,
      typeSelect: 0,
      businessCode: 'train',
      //主分类
      options: null,
      userType: "1",
      sign: '1',
      //报名
      openApplication: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        activityName: null,
        initStartTime: null,
        initEndTime: null
      },
      openUser: false,
      // 列信息
      columns: [
        { key: 0, label: `状态`, prop: "status", visible: true },
        { key: 1, label: `活动名称`, prop: "activityName", visible: true },
        { key: 2, label: `发起单位`, prop: "initiationUnit", visible: true },
        { key: 3, label: `主办单位`, prop: "sponsor", visible: true },
        { key: 4, label: `类别`, prop: "type", visible: true },
        { key: 5, label: `形式`, prop: "lays", visible: true },
        { key: 6, label: `发起时间`, prop: "initiationTime", visible: true },
        { key: 7, label: `开始时间`, prop: "startTime", visible: true },
        { key: 8, label: `结束时间`, prop: "endTime", visible: true },
        { key: 9, label: `地点`, prop: "location", visible: true },
        { key: 10, label: `创建人`, prop: "creationName", visible: true },
        { key: 11, label: `创建时间`, prop: "creationTime", visible: true, },
        { key: 12, label: `联系人`, prop: "contacts", visible: true },
        { key: 13, label: `联系电话`, prop: "telephone", visible: true },
        { key: 14, label: `报名截止`, prop: "deadlineTime", visible: true },
        { key: 15, label: `审核人`, prop: "examineName", visible: true },
        { key: 16, label: `参训人数`, prop: "partPersonNum", visible: true },
        { key: 17, label: `参训企业数量`, prop: "partEnterNum", visible: true },
        { key: 18, label: `是否报名`, prop: "partRecive", visible: true },
      ],
      //行政区域
      optionsArea: null,
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    this.area();
    this.activityId = this.$route.query.activityId;
    // 获取openApplication参数
    if (this.$route.query.open === true) {
      console.log("是否执行" + this.openApplication)
      this.openApplication = this.$route.query.open;
    }else if (this.$route.query.id!==undefined){
      this.form.activityId=this.$route.query.id;
      this.handleScore(this.form.activityId,1);
    }
  },
  methods: {

    /** 查询活动信息培训列表 */
    getList() {
      this.loading = true;
      this.trainingList = [];
      //alert(this.enterpriseId)
      //判断是否从客户跳转进来
      if (this.enterpriseId != "" && this.enterpriseId != null) {
        console.log("是否执行")
        this.queryParams.sponsor = this.enterpriseId//用来暂存客户id
        listTrainingByEnterpriseId(this.queryParams).then(response => {
          this.trainingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        listTrainingRevice(this.queryParams).then(response => {
          this.trainingList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }

    },
    selectUser(userId, userName) {
      this.$set(this.form, 'examineId', userId)
      this.$set(this.form, 'examineName', userName)
    },
    area() {
      listArea({}).then(response => {
        this.optionsArea = response.data;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.areaId,
        label: node.areaName,
        isDisabled: node.parentId == '000000' ? true : false,
        children: node.list.length > 0 ? node.list : 0,
      }
    },
    //关闭对话框
    closeTrain() {
      this.ReadOnly = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //点击接收方文本域,弹出选择当前用户在企业管理中的企业信息
    handleTextAreaFocus() {
      this.openUser = true;
    },
    parseUTCTime(time, format) {
      const date = new Date(time.replace('T', ' ').replace('+08', ''));
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return format.replace('{y}', year).replace('{m}', month).replace('{d}', day).replace('{hh}', hours).replace('{mm}', minutes);
    },
    selectOpen(type) {
      this.userType = 1;
      this.$refs.select.show();
    },
    //获取当前用户在企业管理中的企业信息
    selectEnterprise(selection) {
      this.form.enterpriseId = selection.map(item => item.enterpriseId);
      this.form.receiverName = selection.map(item => item.enterpriseName).join(',');
      console.log(this.form)
      this.close()
    },
    close() {
      this.openUser = false
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        activityName: null,
        initiationUnit: null,
        sponsorId: null,
        sponsor: null,
        undertakerId: null,
        undertaker: null,
        organizerId: null,
        organizer: null,
        type: null,
        initiationTime: null,
        lays: null,
        startTime: null,
        endTime: null,
        location: null,
        receiverId: null,
        receiverName: null,
        operateTime: null,
        status: null,
        operateId: null,
        operateName: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        createId: null,
        creationName: null,
        creationTime: null,
        belongTo: null,
        classificationId: null,
        contacts: null,
        telephone: null,
        deadlineTime: null,
        examineId: null,
        examineName: null,
        fileUpload: null,
        partPersonNum: null,
        partEnterNum: null,
        satisfactionScore: null,
        //客户id数组
        enterpriseId: [],
        sendType: null,
        partRecive: null,//是否报名（针对用户）
        region: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.initStartTime = null;
      this.queryParams.initEndTime = null;
      this.handleQuery();
    },
    //当有值的时候，默认打开对话框为分类群发，没值为一键发送
    sendTrain() {
      if (this.form.receiverName !== null) {
        this.sendType = "groupSend"
      } else {
        this.sendType = "oneClick"
      }
    },
    openPerson() {
      this.getList();
    },
    //序号展示
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 报名操作 */
    handleSelect(row, index) {
      this.activityId = row.activityId;
      this.openApplication = true;
      // receiveApplication(row.activityId).then(res=>{
      //   this.$modal.msgSuccess("报名成功");
      //   this.getList();
      // })
    },
    //查看
    handleScore(activityId, index) {
      getTraining(activityId).then(response => {
        this.form = response.data;
        this.ReadOnly = true;
        this.open = true;
        this.typeSelect = 2;
        this.form.index = index + 1;
        this.addSign = 3;
        this.show = true;
        this.title = "活动信息查看";
      });
    },
    /** 审核按钮 */
    submitForm(activityId) {
      examine(activityId).then(res => {
        this.$modal.msgSuccess("审核");
        this.open = false;
        this.getList();
      })
    },
    //判断活动当前日期是否大于报名日期
    isBeforeDeadline(deadlineTime) {
      const currentTime = new Date();
      const endDateTime = new Date(deadlineTime);
      return currentTime < endDateTime;
    },
  }
};
</script>
